package trans.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import trans.model.Stations;
import trans.support.Constants;
import trans.utils.CommonUtils;
import trans.utils.HibernateUtil;

public class StationDAO {

	@SuppressWarnings("unchecked")
	public static List<Stations> getStations() throws Exception{
		return  HibernateUtil.getSession().createCriteria(Stations.class).list();
	}
	
	public static Stations getStation(Integer stationId){
		return	(Stations) HibernateUtil.get(Stations.class, stationId);
	}
	
	public static void addStation(Stations station,File flag,String flagName) throws Exception{
		station.setFlag(station.getShortName() + "." + CommonUtils.getFileExtention(flagName));
		InputStream is = null;
		OutputStream os = null;
		try {
			 is = new FileInputStream(flag);
			 os = new FileOutputStream(new File(Constants.CONFIG_ATTACH_FOLDER+File.separator+station.getFlag()));
			 byte[] buf = new byte[1024];
			int len = -1;
			while ((len = is.read(buf)) != -1) {
				os.write(buf, 0, len);
			}
			os.flush();
			is.close();
			os.close();
		} catch (Exception e) {
			System.out.println("upload file error :" + e.getMessage());
			is.close();
			os.close();
			throw  e;
		}
		//delete tempFile
		flag.delete();
		HibernateUtil.saveOrUpdate(station);
	}
	
	public static File getFlagFile(String flag) throws Exception{
		return new File(
				Constants.CONFIG_ATTACH_FOLDER + File.separator + flag);
	}
	
	public static void deleteStation(Integer stationId) throws Exception{
		Stations stations = (Stations) HibernateUtil.getSession().get(Stations.class, stationId);
		HibernateUtil.delete(stations);
	}
	
}
